using Microsoft.Extensions.Logging;
using System.Text;
using Uantek.Device.Communication.Models;
using Uantek.Device.Communication.Protocols.Base;
using Uantek.Device.Communication.Protocols.Interfaces;

namespace Uantek.Device.Communication.Protocols.Modbus
{
    /// <summary>
    /// Modbus协议实现
    /// </summary>
    public class ModbusProtocol : BaseDeviceProtocol
    {
        /// <summary>
        /// 协议名称
        /// </summary>
        public override string ProtocolName => "Modbus";

        /// <summary>
        /// 协议版本
        /// </summary>
        public override string Version => "1.0.0";

        /// <summary>
        /// Modbus功能码
        /// </summary>
        public static class FunctionCodes
        {
            public const byte ReadCoils = 0x01;                    // 读取线圈状态
            public const byte ReadDiscreteInputs = 0x02;           // 读取离散输入状态
            public const byte ReadHoldingRegisters = 0x03;         // 读取保持寄存器
            public const byte ReadInputRegisters = 0x04;           // 读取输入寄存器
            public const byte WriteSingleCoil = 0x05;              // 写单个线圈
            public const byte WriteSingleRegister = 0x06;          // 写单个寄存器
            public const byte WriteMultipleCoils = 0x0F;           // 写多个线圈
            public const byte WriteMultipleRegisters = 0x10;       // 写多个寄存器
        }

        /// <summary>
        /// Modbus异常码
        /// </summary>
        public static class ExceptionCodes
        {
            public const byte IllegalFunction = 0x01;              // 非法功能码
            public const byte IllegalDataAddress = 0x02;           // 非法数据地址
            public const byte IllegalDataValue = 0x03;             // 非法数据值
            public const byte SlaveDeviceFailure = 0x04;           // 从设备故障
            public const byte Acknowledge = 0x05;                  // 确认
            public const byte SlaveDeviceBusy = 0x06;               // 从设备忙
            public const byte MemoryParityError = 0x08;            // 存储器奇偶校验错误
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        public ModbusProtocol(ILogger<ModbusProtocol>? logger = null) : base(logger)
        {
        }

        /// <summary>
        /// 获取支持的通信类型
        /// </summary>
        /// <returns>支持的通信类型列表</returns>
        public override IEnumerable<string> GetSupportedTransportTypes()
        {
            return new[] { "TCP", "RTU", "ASCII" };
        }

        /// <summary>
        /// 解析数据的具体实现
        /// </summary>
        /// <param name="rawData">原始数据</param>
        /// <returns>解析后的设备数据</returns>
        protected override async Task<DeviceDataModel?> ParseDataAsync(byte[] rawData)
        {
            try
            {
                LogDebug("开始解析Modbus数据，数据长度: {Length}，数据: {Data}", rawData.Length, BytesToHex(rawData));

                // 检查是否为异常响应
                if (IsExceptionResponse(rawData))
                {
                    return await ParseExceptionResponseAsync(rawData);
                }

                // 根据功能码解析数据
                var functionCode = GetFunctionCode(rawData);
                LogDebug("Modbus功能码: 0x{FunctionCode:X2}", functionCode);

                return functionCode switch
                {
                    FunctionCodes.ReadCoils => await ParseReadCoilsResponseAsync(rawData),
                    FunctionCodes.ReadDiscreteInputs => await ParseReadDiscreteInputsResponseAsync(rawData),
                    FunctionCodes.ReadHoldingRegisters => await ParseReadHoldingRegistersResponseAsync(rawData),
                    FunctionCodes.ReadInputRegisters => await ParseReadInputRegistersResponseAsync(rawData),
                    FunctionCodes.WriteSingleCoil => await ParseWriteSingleCoilResponseAsync(rawData),
                    FunctionCodes.WriteSingleRegister => await ParseWriteSingleRegisterResponseAsync(rawData),
                    FunctionCodes.WriteMultipleCoils => await ParseWriteMultipleCoilsResponseAsync(rawData),
                    FunctionCodes.WriteMultipleRegisters => await ParseWriteMultipleRegistersResponseAsync(rawData),
                    _ => throw new NotSupportedException($"不支持的Modbus功能码: 0x{functionCode:X2}")
                };
            }
            catch (Exception ex)
            {
                LogError(ex, "解析Modbus数据时发生异常");
                throw;
            }
        }

        /// <summary>
        /// 构建命令数据的具体实现
        /// </summary>
        /// <param name="command">命令</param>
        /// <param name="parameters">参数</param>
        /// <returns>命令数据</returns>
        protected override async Task<byte[]> BuildCommandDataAsync(string command, Dictionary<string, object>? parameters)
        {
            try
            {
                LogDebug("开始构建Modbus命令: {Command}", command);

                parameters ??= new Dictionary<string, object>();

                return command.ToUpper() switch
                {
                    "READ_COILS" => await BuildReadCoilsCommandAsync(parameters),
                    "READ_DISCRETE_INPUTS" => await BuildReadDiscreteInputsCommandAsync(parameters),
                    "READ_HOLDING_REGISTERS" => await BuildReadHoldingRegistersCommandAsync(parameters),
                    "READ_INPUT_REGISTERS" => await BuildReadInputRegistersCommandAsync(parameters),
                    "WRITE_SINGLE_COIL" => await BuildWriteSingleCoilCommandAsync(parameters),
                    "WRITE_SINGLE_REGISTER" => await BuildWriteSingleRegisterCommandAsync(parameters),
                    "WRITE_MULTIPLE_COILS" => await BuildWriteMultipleCoilsCommandAsync(parameters),
                    "WRITE_MULTIPLE_REGISTERS" => await BuildWriteMultipleRegistersCommandAsync(parameters),
                    _ => throw new NotSupportedException($"不支持的Modbus命令: {command}")
                };
            }
            catch (Exception ex)
            {
                LogError(ex, "构建Modbus命令时发生异常，命令: {Command}", command);
                throw;
            }
        }

        /// <summary>
        /// 验证数据完整性的具体实现
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>是否有效</returns>
        protected override bool ValidateDataInternal(byte[] data)
        {
            try
            {
                // Modbus RTU最小长度为4字节（地址+功能码+数据+CRC）
                if (data.Length < 4)
                {
                    LogWarning("Modbus数据长度不足，最小长度为4字节，当前长度: {Length}", data.Length);
                    return false;
                }

                // 检查CRC（对于RTU模式）
                if (data.Length >= 6) // 有足够的数据包含CRC
                {
                    var dataWithoutCrc = new byte[data.Length - 2];
                    Array.Copy(data, 0, dataWithoutCrc, 0, data.Length - 2);
                    
                    var calculatedCrc = CalculateCrc16(dataWithoutCrc);
                    var receivedCrc = BitConverter.ToUInt16(data, data.Length - 2);

                    if (calculatedCrc != receivedCrc)
                    {
                        LogWarning("Modbus CRC校验失败，计算值: 0x{CalculatedCrc:X4}，接收值: 0x{ReceivedCrc:X4}", 
                            calculatedCrc, receivedCrc);
                        return false;
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                LogError(ex, "验证Modbus数据时发生异常");
                return false;
            }
        }

        #region 私有方法

        /// <summary>
        /// 获取功能码
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>功能码</returns>
        private static byte GetFunctionCode(byte[] data)
        {
            return data.Length >= 2 ? data[1] : (byte)0;
        }

        /// <summary>
        /// 检查是否为异常响应
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>是否为异常响应</returns>
        private static bool IsExceptionResponse(byte[] data)
        {
            if (data.Length < 2) return false;
            var functionCode = data[1];
            return (functionCode & 0x80) != 0; // 最高位为1表示异常响应
        }

        /// <summary>
        /// 解析异常响应
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>设备数据模型</returns>
        private async Task<DeviceDataModel> ParseExceptionResponseAsync(byte[] data)
        {
            var slaveId = data[0];
            var functionCode = (byte)(data[1] & 0x7F); // 去掉最高位
            var exceptionCode = data[2];

            var result = new DeviceDataModel
            {
                DeviceId = slaveId.ToString(),
                DataType = "ModbusException",
                IsAlarm = true,
                AlarmLevel = "Error",
                AlarmMessage = $"Modbus异常响应，功能码: 0x{functionCode:X2}，异常码: 0x{exceptionCode:X2} ({GetExceptionMessage(exceptionCode)})",
                DataValues = new Dictionary<string, object>
                {
                    ["SlaveId"] = slaveId,
                    ["FunctionCode"] = functionCode,
                    ["ExceptionCode"] = exceptionCode,
                    ["ExceptionMessage"] = GetExceptionMessage(exceptionCode)
                }
            };

            LogWarning("收到Modbus异常响应，从站ID: {SlaveId}，功能码: 0x{FunctionCode:X2}，异常码: 0x{ExceptionCode:X2}", 
                slaveId, functionCode, exceptionCode);

            await Task.CompletedTask;
            return result;
        }

        /// <summary>
        /// 获取异常消息
        /// </summary>
        /// <param name="exceptionCode">异常码</param>
        /// <returns>异常消息</returns>
        private static string GetExceptionMessage(byte exceptionCode)
        {
            return exceptionCode switch
            {
                ExceptionCodes.IllegalFunction => "非法功能码",
                ExceptionCodes.IllegalDataAddress => "非法数据地址",
                ExceptionCodes.IllegalDataValue => "非法数据值",
                ExceptionCodes.SlaveDeviceFailure => "从设备故障",
                ExceptionCodes.Acknowledge => "确认",
                ExceptionCodes.SlaveDeviceBusy => "从设备忙",
                ExceptionCodes.MemoryParityError => "存储器奇偶校验错误",
                _ => $"未知异常码: 0x{exceptionCode:X2}"
            };
        }

        #endregion

        #region 读取响应解析

        /// <summary>
        /// 解析读取线圈响应
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>设备数据模型</returns>
        private async Task<DeviceDataModel> ParseReadCoilsResponseAsync(byte[] data)
        {
            var slaveId = data[0];
            var byteCount = data[2];
            var coilValues = new List<bool>();

            for (int i = 0; i < byteCount; i++)
            {
                var coilByte = data[3 + i];
                for (int bit = 0; bit < 8; bit++)
                {
                    coilValues.Add((coilByte & (1 << bit)) != 0);
                }
            }

            var result = new DeviceDataModel
            {
                DeviceId = slaveId.ToString(),
                DataType = "ModbusCoils",
                DataValues = new Dictionary<string, object>()
            };

            for (int i = 0; i < coilValues.Count; i++)
            {
                result.DataValues[$"Coil_{i}"] = coilValues[i];
            }

            LogDebug("解析线圈数据完成，从站ID: {SlaveId}，线圈数量: {Count}", slaveId, coilValues.Count);

            await Task.CompletedTask;
            return result;
        }

        /// <summary>
        /// 解析读取离散输入响应
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>设备数据模型</returns>
        private async Task<DeviceDataModel> ParseReadDiscreteInputsResponseAsync(byte[] data)
        {
            var slaveId = data[0];
            var byteCount = data[2];
            var inputValues = new List<bool>();

            for (int i = 0; i < byteCount; i++)
            {
                var inputByte = data[3 + i];
                for (int bit = 0; bit < 8; bit++)
                {
                    inputValues.Add((inputByte & (1 << bit)) != 0);
                }
            }

            var result = new DeviceDataModel
            {
                DeviceId = slaveId.ToString(),
                DataType = "ModbusDiscreteInputs",
                DataValues = new Dictionary<string, object>()
            };

            for (int i = 0; i < inputValues.Count; i++)
            {
                result.DataValues[$"Input_{i}"] = inputValues[i];
            }

            LogDebug("解析离散输入数据完成，从站ID: {SlaveId}，输入数量: {Count}", slaveId, inputValues.Count);

            await Task.CompletedTask;
            return result;
        }

        /// <summary>
        /// 解析读取保持寄存器响应
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>设备数据模型</returns>
        private async Task<DeviceDataModel> ParseReadHoldingRegistersResponseAsync(byte[] data)
        {
            var slaveId = data[0];
            var byteCount = data[2];
            var registerCount = byteCount / 2;

            var result = new DeviceDataModel
            {
                DeviceId = slaveId.ToString(),
                DataType = "ModbusHoldingRegisters",
                DataValues = new Dictionary<string, object>()
            };

            for (int i = 0; i < registerCount; i++)
            {
                var registerValue = BitConverter.ToUInt16(data, 3 + i * 2);
                // Modbus使用大端序，需要转换
                registerValue = SwapBytes(registerValue);
                result.DataValues[$"Register_{i}"] = registerValue;
            }

            LogDebug("解析保持寄存器数据完成，从站ID: {SlaveId}，寄存器数量: {Count}", slaveId, registerCount);

            await Task.CompletedTask;
            return result;
        }

        /// <summary>
        /// 解析读取输入寄存器响应
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>设备数据模型</returns>
        private async Task<DeviceDataModel> ParseReadInputRegistersResponseAsync(byte[] data)
        {
            var slaveId = data[0];
            var byteCount = data[2];
            var registerCount = byteCount / 2;

            var result = new DeviceDataModel
            {
                DeviceId = slaveId.ToString(),
                DataType = "ModbusInputRegisters",
                DataValues = new Dictionary<string, object>()
            };

            for (int i = 0; i < registerCount; i++)
            {
                var registerValue = BitConverter.ToUInt16(data, 3 + i * 2);
                // Modbus使用大端序，需要转换
                registerValue = SwapBytes(registerValue);
                result.DataValues[$"Register_{i}"] = registerValue;
            }

            LogDebug("解析输入寄存器数据完成，从站ID: {SlaveId}，寄存器数量: {Count}", slaveId, registerCount);

            await Task.CompletedTask;
            return result;
        }

        #endregion

        #region 写入响应解析

        /// <summary>
        /// 解析写单个线圈响应
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>设备数据模型</returns>
        private async Task<DeviceDataModel> ParseWriteSingleCoilResponseAsync(byte[] data)
        {
            var slaveId = data[0];
            var address = BitConverter.ToUInt16(data, 2);
            address = SwapBytes(address);
            var value = BitConverter.ToUInt16(data, 4);
            value = SwapBytes(value);

            var result = new DeviceDataModel
            {
                DeviceId = slaveId.ToString(),
                DataType = "ModbusWriteSingleCoil",
                DataValues = new Dictionary<string, object>
                {
                    ["Address"] = address,
                    ["Value"] = value == 0xFF00,
                    ["Success"] = true
                }
            };

            LogDebug("写单个线圈响应解析完成，从站ID: {SlaveId}，地址: {Address}，值: {Value}", slaveId, address, value == 0xFF00);

            await Task.CompletedTask;
            return result;
        }

        /// <summary>
        /// 解析写单个寄存器响应
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>设备数据模型</returns>
        private async Task<DeviceDataModel> ParseWriteSingleRegisterResponseAsync(byte[] data)
        {
            var slaveId = data[0];
            var address = BitConverter.ToUInt16(data, 2);
            address = SwapBytes(address);
            var value = BitConverter.ToUInt16(data, 4);
            value = SwapBytes(value);

            var result = new DeviceDataModel
            {
                DeviceId = slaveId.ToString(),
                DataType = "ModbusWriteSingleRegister",
                DataValues = new Dictionary<string, object>
                {
                    ["Address"] = address,
                    ["Value"] = value,
                    ["Success"] = true
                }
            };

            LogDebug("写单个寄存器响应解析完成，从站ID: {SlaveId}，地址: {Address}，值: {Value}", slaveId, address, value);

            await Task.CompletedTask;
            return result;
        }

        /// <summary>
        /// 解析写多个线圈响应
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>设备数据模型</returns>
        private async Task<DeviceDataModel> ParseWriteMultipleCoilsResponseAsync(byte[] data)
        {
            var slaveId = data[0];
            var startAddress = BitConverter.ToUInt16(data, 2);
            startAddress = SwapBytes(startAddress);
            var quantity = BitConverter.ToUInt16(data, 4);
            quantity = SwapBytes(quantity);

            var result = new DeviceDataModel
            {
                DeviceId = slaveId.ToString(),
                DataType = "ModbusWriteMultipleCoils",
                DataValues = new Dictionary<string, object>
                {
                    ["StartAddress"] = startAddress,
                    ["Quantity"] = quantity,
                    ["Success"] = true
                }
            };

            LogDebug("写多个线圈响应解析完成，从站ID: {SlaveId}，起始地址: {StartAddress}，数量: {Quantity}", 
                slaveId, startAddress, quantity);

            await Task.CompletedTask;
            return result;
        }

        /// <summary>
        /// 解析写多个寄存器响应
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>设备数据模型</returns>
        private async Task<DeviceDataModel> ParseWriteMultipleRegistersResponseAsync(byte[] data)
        {
            var slaveId = data[0];
            var startAddress = BitConverter.ToUInt16(data, 2);
            startAddress = SwapBytes(startAddress);
            var quantity = BitConverter.ToUInt16(data, 4);
            quantity = SwapBytes(quantity);

            var result = new DeviceDataModel
            {
                DeviceId = slaveId.ToString(),
                DataType = "ModbusWriteMultipleRegisters",
                DataValues = new Dictionary<string, object>
                {
                    ["StartAddress"] = startAddress,
                    ["Quantity"] = quantity,
                    ["Success"] = true
                }
            };

            LogDebug("写多个寄存器响应解析完成，从站ID: {SlaveId}，起始地址: {StartAddress}，数量: {Quantity}", 
                slaveId, startAddress, quantity);

            await Task.CompletedTask;
            return result;
        }

        #endregion

        #region 命令构建

        /// <summary>
        /// 构建读取线圈命令
        /// </summary>
        /// <param name="parameters">参数</param>
        /// <returns>命令数据</returns>
        private async Task<byte[]> BuildReadCoilsCommandAsync(Dictionary<string, object> parameters)
        {
            var slaveId = GetParameter<byte>(parameters, "SlaveId", 1);
            var startAddress = GetParameter<ushort>(parameters, "StartAddress", 0);
            var quantity = GetParameter<ushort>(parameters, "Quantity", 1);

            var command = new List<byte>
            {
                slaveId,
                FunctionCodes.ReadCoils
            };

            // 添加起始地址（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes(startAddress)));
            // 添加数量（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes(quantity)));

            // 添加CRC
            var crc = CalculateCrc16(command.ToArray());
            command.AddRange(BitConverter.GetBytes(crc));

            LogDebug("构建读取线圈命令完成，从站ID: {SlaveId}，起始地址: {StartAddress}，数量: {Quantity}", 
                slaveId, startAddress, quantity);

            await Task.CompletedTask;
            return command.ToArray();
        }

        /// <summary>
        /// 构建读取离散输入命令
        /// </summary>
        /// <param name="parameters">参数</param>
        /// <returns>命令数据</returns>
        private async Task<byte[]> BuildReadDiscreteInputsCommandAsync(Dictionary<string, object> parameters)
        {
            var slaveId = GetParameter<byte>(parameters, "SlaveId", 1);
            var startAddress = GetParameter<ushort>(parameters, "StartAddress", 0);
            var quantity = GetParameter<ushort>(parameters, "Quantity", 1);

            var command = new List<byte>
            {
                slaveId,
                FunctionCodes.ReadDiscreteInputs
            };

            // 添加起始地址（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes(startAddress)));
            // 添加数量（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes(quantity)));

            // 添加CRC
            var crc = CalculateCrc16(command.ToArray());
            command.AddRange(BitConverter.GetBytes(crc));

            LogDebug("构建读取离散输入命令完成，从站ID: {SlaveId}，起始地址: {StartAddress}，数量: {Quantity}", 
                slaveId, startAddress, quantity);

            await Task.CompletedTask;
            return command.ToArray();
        }

        /// <summary>
        /// 构建读取保持寄存器命令
        /// </summary>
        /// <param name="parameters">参数</param>
        /// <returns>命令数据</returns>
        private async Task<byte[]> BuildReadHoldingRegistersCommandAsync(Dictionary<string, object> parameters)
        {
            var slaveId = GetParameter<byte>(parameters, "SlaveId", 1);
            var startAddress = GetParameter<ushort>(parameters, "StartAddress", 0);
            var quantity = GetParameter<ushort>(parameters, "Quantity", 1);

            var command = new List<byte>
            {
                slaveId,
                FunctionCodes.ReadHoldingRegisters
            };

            // 添加起始地址（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes(startAddress)));
            // 添加数量（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes(quantity)));

            // 添加CRC
            var crc = CalculateCrc16(command.ToArray());
            command.AddRange(BitConverter.GetBytes(crc));

            LogDebug("构建读取保持寄存器命令完成，从站ID: {SlaveId}，起始地址: {StartAddress}，数量: {Quantity}", 
                slaveId, startAddress, quantity);

            await Task.CompletedTask;
            return command.ToArray();
        }

        /// <summary>
        /// 构建读取输入寄存器命令
        /// </summary>
        /// <param name="parameters">参数</param>
        /// <returns>命令数据</returns>
        private async Task<byte[]> BuildReadInputRegistersCommandAsync(Dictionary<string, object> parameters)
        {
            var slaveId = GetParameter<byte>(parameters, "SlaveId", 1);
            var startAddress = GetParameter<ushort>(parameters, "StartAddress", 0);
            var quantity = GetParameter<ushort>(parameters, "Quantity", 1);

            var command = new List<byte>
            {
                slaveId,
                FunctionCodes.ReadInputRegisters
            };

            // 添加起始地址（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes(startAddress)));
            // 添加数量（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes(quantity)));

            // 添加CRC
            var crc = CalculateCrc16(command.ToArray());
            command.AddRange(BitConverter.GetBytes(crc));

            LogDebug("构建读取输入寄存器命令完成，从站ID: {SlaveId}，起始地址: {StartAddress}，数量: {Quantity}", 
                slaveId, startAddress, quantity);

            await Task.CompletedTask;
            return command.ToArray();
        }

        /// <summary>
        /// 构建写单个线圈命令
        /// </summary>
        /// <param name="parameters">参数</param>
        /// <returns>命令数据</returns>
        private async Task<byte[]> BuildWriteSingleCoilCommandAsync(Dictionary<string, object> parameters)
        {
            var slaveId = GetParameter<byte>(parameters, "SlaveId", 1);
            var address = GetParameter<ushort>(parameters, "Address", 0);
            var value = GetParameter<bool>(parameters, "Value", false);

            var command = new List<byte>
            {
                slaveId,
                FunctionCodes.WriteSingleCoil
            };

            // 添加地址（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes(address)));
            // 添加值（大端序）
            var coilValue = value ? (ushort)0xFF00 : (ushort)0x0000;
            command.AddRange(BitConverter.GetBytes(SwapBytes(coilValue)));

            // 添加CRC
            var crc = CalculateCrc16(command.ToArray());
            command.AddRange(BitConverter.GetBytes(crc));

            LogDebug("构建写单个线圈命令完成，从站ID: {SlaveId}，地址: {Address}，值: {Value}", 
                slaveId, address, value);

            await Task.CompletedTask;
            return command.ToArray();
        }

        /// <summary>
        /// 构建写单个寄存器命令
        /// </summary>
        /// <param name="parameters">参数</param>
        /// <returns>命令数据</returns>
        private async Task<byte[]> BuildWriteSingleRegisterCommandAsync(Dictionary<string, object> parameters)
        {
            var slaveId = GetParameter<byte>(parameters, "SlaveId", 1);
            var address = GetParameter<ushort>(parameters, "Address", 0);
            var value = GetParameter<ushort>(parameters, "Value", 0);

            var command = new List<byte>
            {
                slaveId,
                FunctionCodes.WriteSingleRegister
            };

            // 添加地址（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes(address)));
            // 添加值（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes(value)));

            // 添加CRC
            var crc = CalculateCrc16(command.ToArray());
            command.AddRange(BitConverter.GetBytes(crc));

            LogDebug("构建写单个寄存器命令完成，从站ID: {SlaveId}，地址: {Address}，值: {Value}", 
                slaveId, address, value);

            await Task.CompletedTask;
            return command.ToArray();
        }

        /// <summary>
        /// 构建写多个线圈命令
        /// </summary>
        /// <param name="parameters">参数</param>
        /// <returns>命令数据</returns>
        private async Task<byte[]> BuildWriteMultipleCoilsCommandAsync(Dictionary<string, object> parameters)
        {
            var slaveId = GetParameter<byte>(parameters, "SlaveId", 1);
            var startAddress = GetParameter<ushort>(parameters, "StartAddress", 0);
            var values = GetParameter<bool[]>(parameters, "Values", Array.Empty<bool>());

            var command = new List<byte>
            {
                slaveId,
                FunctionCodes.WriteMultipleCoils
            };

            // 添加起始地址（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes(startAddress)));
            // 添加数量（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes((ushort)values.Length)));

            // 计算字节数
            var byteCount = (byte)((values.Length + 7) / 8);
            command.Add(byteCount);

            // 添加线圈值
            for (int i = 0; i < byteCount; i++)
            {
                byte coilByte = 0;
                for (int bit = 0; bit < 8 && i * 8 + bit < values.Length; bit++)
                {
                    if (values[i * 8 + bit])
                    {
                        coilByte |= (byte)(1 << bit);
                    }
                }
                command.Add(coilByte);
            }

            // 添加CRC
            var crc = CalculateCrc16(command.ToArray());
            command.AddRange(BitConverter.GetBytes(crc));

            LogDebug("构建写多个线圈命令完成，从站ID: {SlaveId}，起始地址: {StartAddress}，数量: {Quantity}", 
                slaveId, startAddress, values.Length);

            await Task.CompletedTask;
            return command.ToArray();
        }

        /// <summary>
        /// 构建写多个寄存器命令
        /// </summary>
        /// <param name="parameters">参数</param>
        /// <returns>命令数据</returns>
        private async Task<byte[]> BuildWriteMultipleRegistersCommandAsync(Dictionary<string, object> parameters)
        {
            var slaveId = GetParameter<byte>(parameters, "SlaveId", 1);
            var startAddress = GetParameter<ushort>(parameters, "StartAddress", 0);
            var values = GetParameter<ushort[]>(parameters, "Values", Array.Empty<ushort>());

            var command = new List<byte>
            {
                slaveId,
                FunctionCodes.WriteMultipleRegisters
            };

            // 添加起始地址（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes(startAddress)));
            // 添加数量（大端序）
            command.AddRange(BitConverter.GetBytes(SwapBytes((ushort)values.Length)));

            // 字节数
            var byteCount = (byte)(values.Length * 2);
            command.Add(byteCount);

            // 添加寄存器值（大端序）
            foreach (var value in values)
            {
                command.AddRange(BitConverter.GetBytes(SwapBytes(value)));
            }

            // 添加CRC
            var crc = CalculateCrc16(command.ToArray());
            command.AddRange(BitConverter.GetBytes(crc));

            LogDebug("构建写多个寄存器命令完成，从站ID: {SlaveId}，起始地址: {StartAddress}，数量: {Quantity}", 
                slaveId, startAddress, values.Length);

            await Task.CompletedTask;
            return command.ToArray();
        }

        #endregion

        #region 辅助方法

        /// <summary>
        /// 获取参数值
        /// </summary>
        /// <typeparam name="T">参数类型</typeparam>
        /// <param name="parameters">参数字典</param>
        /// <param name="key">参数键</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>参数值</returns>
        private static T GetParameter<T>(Dictionary<string, object> parameters, string key, T defaultValue)
        {
            if (parameters.TryGetValue(key, out var value))
            {
                try
                {
                    return (T)Convert.ChangeType(value, typeof(T));
                }
                catch
                {
                    return defaultValue;
                }
            }
            return defaultValue;
        }

        #endregion

        #region 连接和通信方法实现

        /// <summary>
        /// 连接设备的具体实现
        /// </summary>
        /// <returns>连接结果</returns>
        protected override async Task<CommunicationResult> ConnectDeviceAsync()
        {
            try
            {
                LogInformation("Modbus设备连接开始");
                
                // 这里应该实现具体的连接逻辑
                // 由于Modbus协议本身是无连接的，这里主要是验证传输层连接
                
                // 模拟连接过程
                await Task.Delay(100);
                
                LogInformation("Modbus设备连接成功");
                return CommunicationResult.Ok("Modbus设备连接成功");
            }
            catch (Exception ex)
            {
                LogError(ex, "Modbus设备连接失败");
                return CommunicationResult.Failed($"Modbus设备连接失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 断开设备连接的具体实现
        /// </summary>
        /// <returns>断开结果</returns>
        protected override async Task<CommunicationResult> DisconnectDeviceAsync()
        {
            try
            {
                LogInformation("Modbus设备断开连接开始");
                
                // 这里应该实现具体的断开连接逻辑
                
                // 模拟断开过程
                await Task.Delay(50);
                
                LogInformation("Modbus设备断开连接成功");
                return CommunicationResult.Ok("Modbus设备断开连接成功");
            }
            catch (Exception ex)
            {
                LogError(ex, "Modbus设备断开连接失败");
                return CommunicationResult.Failed($"Modbus设备断开连接失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 发送设备命令的具体实现
        /// </summary>
        /// <param name="command">命令</param>
        /// <param name="parameters">参数</param>
        /// <returns>命令执行结果</returns>
        protected override async Task<CommunicationResult<string>> SendDeviceCommandAsync(string command, Dictionary<string, object>? parameters)
        {
            try
            {
                LogInformation("发送Modbus命令: {Command}", command);
                
                // 构建命令数据
                var commandData = await BuildCommandDataAsync(command, parameters);
                
                // 这里应该通过传输层发送命令并接收响应
                // 目前返回模拟结果
                var result = $"命令 {command} 执行成功，发送数据长度: {commandData.Length}";
                
                LogInformation("Modbus命令执行成功: {Command}", command);
                return CommunicationResult<string>.Ok(result, "命令执行成功");
            }
            catch (Exception ex)
            {
                LogError(ex, "Modbus命令执行失败: {Command}", command);
                return CommunicationResult<string>.Failed($"命令执行失败: {ex.Message}");
            }
        }

        #endregion
    }
}